﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Zhaoxi.FactoryDeviceSystem.Models;
using Zhaoxi.FactoryDeviceSystem.Utils;

namespace Zhaoxi.FactoryDeviceSystem
{
    public partial class FrmDeviceSetting : Form
    {
        public FrmDeviceSetting()
        {
            InitializeComponent();
          
        }

        private void FrmDeviceSetting_Load(object sender, EventArgs e)
        {
            if(!Directory.Exists(CommonHelper.folder))
                Directory.CreateDirectory(CommonHelper.folder);
            if(CommonHelper.deviceList.Count>0)
            {
                ReloadDeviceList();
            }
            InitAdd();
        }

        private void InitAdd()
        {
            //左侧信息栏---重置为新增设备状态
            int count = CommonHelper.deviceList.Count;
            if (count > 0)
            {
                int lastNo = CommonHelper.deviceList[count - 1].DeviceNo + 1;
                txtDevNo.Text = lastNo.ToString();
            }
            else
            {
                txtDevNo.Text = "1";
            }
            txtDevName.Text = txtDevNo.Text + "#设备";
            txtPosition.Text = "0";
            txtStateAddr.Text = "0.0";
            txtDevNo.ReadOnly = false;
            selNo = 0;
        }

        private void ReloadDeviceList()
        {
            lbDevList.Items.Clear();
            foreach (var dev in CommonHelper.deviceList)
            {
                lbDevList.Items.Add("  "+dev.DeviceNo + "    " + dev.DeviceName);
            }
        }

        bool isSaved = false;//是否已保存
        int selNo = 0;//选择的设备编号
        //新增、修改设备保存
        private void btnOk_Click(object sender, EventArgs e)
        {
            //接收信息
            int devNo = txtDevNo.Text.GetInt();
            string devName = txtDevName.Text.Trim();
            int position = txtPosition.Text.GetInt();
            string stateAddr = txtStateAddr.Text.Trim();
            //刷新到设备列表
            if(selNo>0)//修改
            {
                DeviceInfo dev = CommonHelper.deviceList.Find(d => d.DeviceNo == selNo);
                dev.DeviceName = devName;
                dev.Position = position;
                dev.StateAddress = stateAddr;
            }
            else//新增
            {
                CommonHelper.deviceList.Add(new Models.DeviceInfo()
                {
                    DeviceNo = devNo,
                    DeviceName = devName,
                    Position = position,
                    StateAddress = stateAddr
                });
            }
            //写到文件
            SaveToFile();
            InitAdd();
            isSaved = true;
        }

        private void SaveToFile()
        {
             string json=JsonConvert.SerializeObject(CommonHelper.deviceList);//序列化
             File.WriteAllText(CommonHelper.devicesPath, json);//写入到json文件

            MessageHelper.Success("设备信息配置", "设备信息保存成功！");
            ReloadDeviceList();
            CommonHelper.IsUpdateDevices = true;//已更改了设备配置
        }

        /// <summary>
        /// 选择设备加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbDevList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(lbDevList.SelectedItem != null)
            {
                string selItem=lbDevList.SelectedItem.ToString();
                string[] arr=selItem.Split(' ').Where(s=>s!="").ToArray();//信息项数组
                int devNo = arr[0].GetInt();//设备编号 
                string devName = arr[1];//设备名称
                DeviceInfo dev=CommonHelper.deviceList.Find(d=>d.DeviceNo== devNo);
                if(dev!=null)
                {
                    //加载设备信息到信息栏
                    txtDevNo.Text = devNo.ToString();
                    txtDevName.Text = devName;
                    txtPosition.Text=dev.Position.ToString();
                    txtStateAddr.Text = dev.StateAddress;
                    txtDevNo.ReadOnly = true;//只读
                }
                selNo = devNo;//暂存选择的设备编号
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            InitAdd();
        }

        //关闭窗口
        private void btnClose_Click(object sender, EventArgs e)
        {
            if (isSaved == false)
            {
                if (MessageHelper.Question("关闭提示", "当前未保存，是否确定要关闭窗口？") == DialogResult.OK)
                {
                    this.Close();
                }
                else
                {
                    return;
                }
            }
            else
                this.Close();
        }

        private void txtDevName_TextChanged(object sender, EventArgs e)
        {
            isSaved = false;
        }

        /// <summary>
        /// 设备删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            DeviceInfo dev = CommonHelper.deviceList.Find(d => d.DeviceNo == selNo);
            if(dev!=null)
            {
                if(MessageHelper.Question("删除设备","你确定要删除该设备信息吗？")==DialogResult.OK)
                {
                    CommonHelper.deviceList.Remove(dev);
                    SaveToFile();
                    isSaved = true;
                }
            }
        }
    }
}
